package com.smartaccounting.controller;

import com.smartaccounting.dao.IncomeDAO;
import com.smartaccounting.model.Income;
import com.smartaccounting.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.time.LocalDate;

@WebServlet("/income")
public class IncomeServlet extends HttpServlet {
    private IncomeDAO incomeDAO;

    @Override
    public void init() throws ServletException {
        incomeDAO = new IncomeDAO();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            switch (action) {
                case "list":
                    listIncomes(request, response);
                    break;
                case "new":
                    showNewForm(request, response);
                    break;
                case "edit":
                    showEditForm(request, response);
                    break;
                case "delete":
                    deleteIncome(request, response);
                    break;
                default:
                    listIncomes(request, response);
                    break;
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");

        try {
            switch (action) {
                case "insert":
                    insertIncome(request, response);
                    break;
                case "update":
                    updateIncome(request, response);
                    break;
            }
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    private void listIncomes(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        String monthYear = request.getParameter("monthYear");
        if (monthYear == null) {
            monthYear = LocalDate.now().getYear() + "-" + String.format("%02d", LocalDate.now().getMonthValue());
        }

        request.setAttribute("incomes", incomeDAO.getIncomesByUserIdAndMonth(user.getUserId(), monthYear));
        request.setAttribute("monthYear", monthYear);
        request.getRequestDispatcher("user/income.jsp").forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("user/income-form.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int incomeId = Integer.parseInt(request.getParameter("incomeId"));
        Income existingIncome = incomeDAO.getIncomeById(incomeId);
        request.setAttribute("income", existingIncome);
        request.getRequestDispatcher("user/income-form.jsp").forward(request, response);
    }

    private void insertIncome(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        BigDecimal amount = new BigDecimal(request.getParameter("amount"));
        String category = request.getParameter("category");
        String source = request.getParameter("source");
        LocalDate incomeDate = LocalDate.parse(request.getParameter("incomeDate"));
        String description = request.getParameter("description");

        Income newIncome = new Income(user.getUserId(), amount, category, source, incomeDate, description);
        incomeDAO.addIncome(newIncome);
        response.sendRedirect("income?action=list");
    }

    private void updateIncome(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        int incomeId = Integer.parseInt(request.getParameter("incomeId"));
        BigDecimal amount = new BigDecimal(request.getParameter("amount"));
        String category = request.getParameter("category");
        String source = request.getParameter("source");
        LocalDate incomeDate = LocalDate.parse(request.getParameter("incomeDate"));
        String description = request.getParameter("description");

        Income income = new Income(incomeId, 0, amount, category, source, incomeDate, description, null);
        incomeDAO.updateIncome(income);
        response.sendRedirect("income?action=list");
    }

    private void deleteIncome(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        int incomeId = Integer.parseInt(request.getParameter("incomeId"));
        incomeDAO.deleteIncome(incomeId);
        response.sendRedirect("income?action=list");
    }
}